package com.neomanager.bbs.web;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.neomanager.bbs.dao.CombineDao;
import com.neomanager.common.dao.CommonDao;
import com.neomanager.login.model.AdminInfo;
import com.util.FileUtil;
import com.util.UtilCommon;

@Controller
@SessionAttributes("adminInfo")
public class CombineController {

	private final Logger logger = Logger.getLogger(this.getClass());
	@Resource(name="CombineDao")
	CombineDao combine;
	@Resource(name="CommonDao")
	CommonDao commonDao;
	/**
	 * 통합게시판 목록 호출
	 */
	@RequestMapping(value = "/bbs/{bbs_id}_list.do", method = RequestMethod.GET)
	public String listCombinemng(
			@PathVariable String bbs_id,
			@RequestParam Map<String, Object> commandMap,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response)

	{
		logger.info("통합게시판 목록.");
		HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		//게시판 조회
		Map<String, Object> bbsMap = combine.selectCombineBBSInfo(bbs_id);
		
		//해당 게시판의 list count
		int bbs_list_count = Integer.parseInt( bbsMap.get("BBS_LIST_COUNT").toString() );
		// 현재 페이지
		int page = 1;
		if (commandMap.get("page") != null)
			page = Integer.parseInt(commandMap.get("page").toString());

		// 페이지당 목록 수
		int pageCount = bbs_list_count;

		// 시작번호
		int startNo = (page - 1) * pageCount;

		commandMap.put("page", page);
		commandMap.put("pageCount", pageCount);
		commandMap.put("bbs_id", bbs_id);

		String skin = (String) bbsMap.get("BBS_SKIN");

		//게시물 조회
		ArrayList<Map<String, Object>> listMap1 = combine.selectCombineBBSList1(commandMap);
		ArrayList<Map<String, Object>> listMap2 = combine.selectCombineBBSList2(commandMap);
		
		
		// 총 갯수
		int totalCount = 0;
		if ( listMap2 != null && listMap2.size() > 0 )
		{
			Map<String, Object> rs = listMap2.get(0);
			totalCount = Integer.parseInt( rs.get("TOTALCOUNT").toString() );
		}
		startNo = totalCount - startNo;

		// 페이징 처리
		if (totalCount > 0)
		{
			UtilCommon util = new UtilCommon();
			// 총게시물수, 페이지당 목록수, 현재페이지, 블럭당 나타낼 페이지 수
			util.setPage(totalCount, pageCount, page, 10);
			commandMap.put("totalCount", totalCount);
			commandMap.put("totalPage", util.getTotalPage());
			commandMap.put("startPage", util.getStartPage());
			commandMap.put("endPage", util.getEndPage());
			commandMap.put("startNo", startNo);
		}
		
		//첨부파일 조회 (대한민국선거 총람)
		if (bbs_id.equals("20140430230125462100"))
		{
			ArrayList<Map<String, Object>> fileListMap = commonDao.selectFileInfoList(commandMap);
			model.addAttribute("fileListMap", fileListMap);
		}

		model.addAttribute("host_name", UtilCommon.host);
		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);
		model.addAttribute("commandMap", commandMap);
		model.addAttribute("bbsMap", bbsMap);
		model.addAttribute("listMap1", listMap1);
		model.addAttribute("listMap2", listMap2);

		return "bbs/"+skin+"/list";
	}

	/**
	 * 통합게시판 조회화면 호출
	 */
	@RequestMapping(value = "/bbs/{bbs_id}_view.do", method = RequestMethod.GET)
	public String viewCombinemng(
			@PathVariable String bbs_id,
			@RequestParam("article_id") String article_id,
			@RequestParam Map<String, Object> commandMap,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		logger.info("통합게시판 조회 화면.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		commandMap.put("bbs_id", bbs_id);
		combine.updateCombineHit(commandMap);

		//게시판 조회
		Map<String, Object> bbsMap = combine.selectCombineBBSInfo(bbs_id);
		String skin = (String) bbsMap.get("BBS_SKIN");
		commandMap.put("bbs_id", bbs_id);
		commandMap.put("article_id", article_id);
		commandMap.put("file_job_id",bbs_id);

		//게시물 조회
		Map<String, Object> viewMap = combine.selectCombineBBSView(commandMap);
		String file_relate_id = (String) viewMap.get("FILE_RELATE_ID");
		commandMap.put("file_relate_id", file_relate_id);

		//첨부파일 조회
		ArrayList<Map<String, Object>> fileListMap = commonDao.selectFileInfoList(commandMap);
		viewMap.put("file_count", fileListMap.size());

		//코멘트 조회
		commandMap.put("job_id",bbs_id);
		commandMap.put("relate_id", article_id);
		ArrayList<Map<String, Object>> commentList = commonDao.selectCommentList(commandMap);

		model.addAttribute("host_name", UtilCommon.host);
		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);
		model.addAttribute("bbsMap", bbsMap);
		model.addAttribute("viewMap", viewMap);
		model.addAttribute("fileListMap", fileListMap);
		model.addAttribute("commentList", commentList);

		return "bbs/"+skin+"/view";
	}

	/**
	 * 통합게시판 등록화면 호출
	 */
	@RequestMapping(value = "/bbs/{bbs_id}_write.do", method = RequestMethod.GET)
	public String writeCombinemng(
			@PathVariable String bbs_id,
			@RequestParam Map<String, Object> commandMap,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		logger.info("통합게시판 등록 화면.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		//게시판 조회
		Map<String, Object> bbsMap =combine.selectCombineBBSInfo(bbs_id);

		String skin = (String) bbsMap.get("BBS_SKIN");

		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);
		model.addAttribute("bbsMap", bbsMap);

		return "bbs/"+skin+"/write";
	}

	/**
	 * 통합게시판 수정화면 호출
	 */
	@RequestMapping(value = "/bbs/{bbs_id}_edit.do", method = RequestMethod.GET)
	public String editCombinemng(
			@PathVariable String bbs_id,
			@RequestParam Map<String, Object> commandMap,
			@RequestParam("article_id") String article_id,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		logger.info("통합게시판 수정 화면.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		//게시판 조회
		Map<String, Object> bbsMap =combine.selectCombineBBSInfo(bbs_id);
		String skin = (String) bbsMap.get("BBS_SKIN");

		//게시판 조회
		commandMap.put("bbs_id", bbs_id);
		commandMap.put("article_id", article_id);
		commandMap.put("file_job_id",bbs_id);

		Map<String, Object> viewMap = combine.selectCombineBBSView(commandMap);
		String file_relate_id = (String) viewMap.get("FILE_RELATE_ID");

		//첨부파일 조회
		commandMap.put("file_relate_id", file_relate_id);
		ArrayList<Map<String, Object>> fileListMap = commonDao.selectFileInfoList(commandMap);
		viewMap.put("FILE_COUNT", fileListMap.size());

		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);
		model.addAttribute("bbsMap", bbsMap);
		model.addAttribute("viewMap", viewMap);
		model.addAttribute("fileListMap", fileListMap);

		return "bbs/"+skin+"/edit";
	}

	/**
	 * 통합게시판 삭제
	 */
	@RequestMapping(value = "/bbs/{bbs_id}_delete.do", method = RequestMethod.GET)
	public String deleteCombinemng(
			@PathVariable String bbs_id,
			@RequestParam Map<String, Object> commandMap,
			@RequestParam("article_id") String article_id,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		logger.info("통합게시판 삭제.");

		//게시판 조회
		commandMap.put("bbs_id", bbs_id);
		commandMap.put("article_id", article_id);
		commandMap.put("file_job_id",bbs_id);

		combine.insertCombineInfo(commandMap);

		return "redirect:../bbs/{bbs_id}_list.do";
	}

	/**
	 * 통합게시판 삭제
	 */
	@RequestMapping(value = "/bbs/{bbs_id}_file_delete.do", method = RequestMethod.GET)
	public String deleteCombineFile(
			@PathVariable String bbs_id,
			@RequestParam Map<String, Object> commandMap,
			@RequestParam("article_id") String article_id,
			@RequestParam("file_id") String file_id,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		logger.info("통합게시판 첨부파일 삭제.");

		commandMap.put("file_job_id", bbs_id);
		commandMap.put("file_id", file_id);
		Map<String, Object> fileMap =commonDao.selectFileInfoView(commandMap);
		String file_relate_id = (String) fileMap.get("FILE_RELATE_ID");
		String file_path = (String) fileMap.get("FILE_PATH");
		String file_rename = (String) fileMap.get("FILE_RENAME");

		Map<String, Object> deleteFileMap = new HashMap<String, Object>();

		deleteFileMap.put("file_job_id", bbs_id);
		deleteFileMap.put("file_id", file_id);
		deleteFileMap.put("file_relate_id", file_relate_id);

		String filePath = file_path + file_rename;
		FileUtil.doMulitFileDelete(filePath); //첨부파일 삭제
		commonDao.deleteFileInfo(deleteFileMap); //첨부파일 정보 삭제

		if(commandMap.get("type").toString().equals("view"))
		{
			return "redirect:../bbs/"+bbs_id+"_view.do?article_id="+article_id;
		}	
		else if(commandMap.get("type").toString().equals("edit"))
		{
			return "redirect:../bbs/"+bbs_id+"_edit.do?article_id="+article_id;
		}	

		return null;
	}

	/**
	 * 통합게시판 답글
	 */
	@RequestMapping(value = "/bbs/{bbs_id}_follow.do", method = RequestMethod.GET)
	public String replyCombinemng(
			@PathVariable String bbs_id,
			@RequestParam Map<String, Object> commandMap,
			@RequestParam("article_id") String article_id,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		logger.info("통합게시판 답글.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		//게시판 조회
		Map<String, Object> bbsMap =combine.selectCombineBBSInfo(bbs_id);
		String skin = (String) bbsMap.get("BBS_SKIN");

		//게시판 조회
		commandMap.put("bbs_id", bbs_id);
		commandMap.put("article_id", article_id);
		commandMap.put("file_job_id",bbs_id);
		Map<String, Object> viewMap = combine.selectCombineBBSView(commandMap);

		bbsMap.put("article_id", article_id);

		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);
		model.addAttribute("bbsMap", bbsMap);
		model.addAttribute("viewMap", viewMap);

		return "bbs/"+skin+"/follow";
	}

	/**
	 * 통합게시판 리플
	 */
	@RequestMapping(value = "/bbs/comment.do", method = RequestMethod.GET)
	public String commentCombinemng(
			@RequestParam("bbs_id") String bbs_id,
			@RequestParam("article_id") String article_id,
			@RequestParam Map<String, Object> commandMap,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		logger.info("통합게시판 리플.");

		return "common/comment";
	}

	/**
	 * 통합게시판 등록/수정/삭제 처리
	 * @throws Exception
	 */
	@RequestMapping(value = "/bbs/{bbs_id}_proc.do", method = RequestMethod.POST)
	public String processCombinemng(
			@PathVariable String bbs_id,
			@RequestParam Map<String, Object> commandMap,
			Model model,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		logger.debug("통합게시판 등록/수정/삭제 처리.");
		
		String redirectUrl = "redirect:../bbs/"+bbs_id+"_list.do";
		if(commandMap.get("mode").toString().equals("write"))
		{
			//첨부파일 ID 생성
			String file_relate_id = UtilCommon.idMake("F");
			commandMap.put("file_relate_id", file_relate_id);
			
			// 폴더 파일 저장
			Properties props = new Properties();
			props.load(new java.io.BufferedInputStream( getClass().getClassLoader().getResourceAsStream("config.properties")) );
			String strFilePath = props.getProperty("uploadsDir").trim();

			String pathUrl = "/uploads/" + bbs_id;
			strFilePath = strFilePath + File.separator + bbs_id;
			
	        Map<String, Map<String, String>> fileInfoMap = FileUtil.doMultiFileUpLoad(request, strFilePath, pathUrl);
	        Map<String, String> fileMap = new HashMap<String, String>();
			if (fileInfoMap != null)
			{
			    Iterator<String> iterator = fileInfoMap.keySet().iterator();
			    while (iterator.hasNext())
			    {
			    	//첨부파일 ID 생성
					String file_id = UtilCommon.idMake("");
			        String key = iterator.next();
			        fileMap = fileInfoMap.get(key);
			        fileMap.put("FILE_ID",file_id);
			        fileMap.put("FILE_RELATE_ID", file_relate_id);
			        fileMap.put("FILE_JOB_ID", bbs_id);
			        commonDao.processFileUpload(fileMap);
			    }
			}

			String article_id = UtilCommon.idMake("");
			commandMap.put("article_id", article_id);
			commandMap.put("article_ref", article_id);
			commandMap.put("article_step", 0);
			commandMap.put("article_depth", 0);
			combine.insertCombineInfo(commandMap);
		}
		else if(commandMap.get("mode").toString().equals("edit"))
		{
			
			//첨부파일 등록
			String file_relate_id = (String) commandMap.get("file_relate_id");
			commandMap.put("file_relate_id", file_relate_id);
			
			// 폴더 파일 저장
			Properties props = new Properties();
			props.load(new java.io.BufferedInputStream( getClass().getClassLoader().getResourceAsStream("config.properties")) );
			String strFilePath = props.getProperty("uploadsDir").trim();

			String pathUrl = "/uploads/" + bbs_id;
			strFilePath = strFilePath + File.separator + bbs_id;

	        Map<String, Map<String, String>> fileInfoMap = FileUtil.doMultiFileUpLoad(request, strFilePath, pathUrl);
	        Map<String, String> fileMap = new HashMap<String, String>();
			if (fileInfoMap != null)
			{
			    Iterator<String> iterator = fileInfoMap.keySet().iterator();
			    while (iterator.hasNext())
			    {
			    	//첨부파일 ID 생성
					String file_id = UtilCommon.idMake("");
			        String key = iterator.next();
			        fileMap = fileInfoMap.get(key);
			        fileMap.put("FILE_ID",file_id);
			        fileMap.put("FILE_RELATE_ID", file_relate_id);
			        fileMap.put("FILE_JOB_ID", bbs_id);
			        commonDao.processFileUpload(fileMap);
			    }
			}

			combine.updateCombineInfo(commandMap);
		}
		else if(commandMap.get("mode").toString().equals("delete"))
		{
			combine.deleteCombineInfo(commandMap);
		}
		else if(commandMap.get("mode").toString().equals("follow"))
		{
			//step + 1 update
			Map<String, Object> viewMap =combine.selectCombineBBSView(commandMap);
			int article_step = Integer.parseInt( viewMap.get("ARTICLE_STEP").toString() );
			int article_depth = Integer.parseInt( viewMap.get("ARTICLE_DEPTH").toString() );
			String article_ref = (String) viewMap.get("ARTICLE_REF");

			commandMap.put("article_step",article_step);
			commandMap.put("article_depth",article_depth);
			commandMap.put("article_ref",article_ref);
			combine.updateCombineStep(commandMap);

			//첨부파일 ID 생성
			String file_relate_id = UtilCommon.idMake("F");
			commandMap.put("file_relate_id", file_relate_id);

			// 폴더 파일 저장
			Properties props = new Properties();
			props.load(new java.io.BufferedInputStream( getClass().getClassLoader().getResourceAsStream("config.properties")) );
			String strFilePath = props.getProperty("uploadsDir").trim();

			String pathUrl = "/uploads/" + bbs_id;
			strFilePath = strFilePath + File.separator + bbs_id;
			
	        Map<String, Map<String, String>> fileInfoMap = FileUtil.doMultiFileUpLoad(request, strFilePath, pathUrl);
	        Map<String, String> fileMap = new HashMap<String, String>();
			if (fileInfoMap != null)
			{
				Iterator<String> iterator = fileInfoMap.keySet().iterator();
				while (iterator.hasNext())
				{
					//첨부파일 ID 생성
					String file_id = UtilCommon.idMake("");
					String key = iterator.next();
					fileMap = fileInfoMap.get(key);
					fileMap.put("FILE_ID",file_id);
					fileMap.put("FILE_RELATE_ID", file_relate_id);
					fileMap.put("FILE_JOB_ID", bbs_id);
					commonDao.processFileUpload(fileMap);
				}
			}

			String id = UtilCommon.idMake("");
			commandMap.put("article_id", id);
			commandMap.put("article_ref", article_ref);
			commandMap.put("article_notice_yn", "N");
			article_step = article_step + 1;
			commandMap.put("article_step",article_step);
			article_depth = article_depth + 1;
			commandMap.put("article_depth",article_depth);

			combine.insertCombineInfo(commandMap);
		}
		else if(commandMap.get("mode").toString().equals("etc"))
		{
			combine.updateCombineEtc(commandMap);
		}
		return redirectUrl;
	}

}
